class ChatroomController < ApplicationController
  layout "chatroom"
  before_filter :authorize
  before_filter :current_room
  
  def index
    @current_users = @current_chatroom.users
  end
  
  def join
    begin
      @chatroom = Chatroom.find(params[:id])
    rescue
      chat_error "Chatroom not found!"
    else
      if @chatroom.scope == 1
        if @chatroom.users << @current_user
          flash[:notice] = "Chatroom joined!"
          redirect_to :action => :index
        else
          chat_error "Error when trying to join chatroom"
        end
      else
        if request.post?
          password = Chatroom.encrypted_password(params[:password], @chatroom.password_salt)
          if @chatroom.password_hashed == password
            if @chatroom.users << @current_user
              flash[:notice] = "Chatroom joined!"
              redirect_to :action => :index
            else
              chat_error "Error when trying to join chatroom"
            end
          else
            chat_error("Wrong password!")
          end
        else
          chat_error "The chatroom is private!"
        end
      end
    end
  end
  
  def join_private
    @id = params[:id]
    render :update do |page|
      page.replace_html 'popup', :partial => "/partials/passwordbox"
      page['wrap'].visual_effect(:opacity, {:duration => 0.1, :from => 1.0, :to => 0.7})
      page['passwordbox'].visual_effect :appear, {:duration => 0.50}
    end
  end
  
  def leave
    @current_user.chatroom = nil
    @current_user.save
    redirect_to :controller => :chat
  end
  
  def send_message
    if request.xhr?
      @message = Message.new(params[:message])
      @message.user = @current_user
      if @current_chatroom.messages << @message
        render :partial => "messages"
      else
        render :text => "Message empty!"
      end
    end
  end
  
  def update_messages
    if request.xhr?
      if @current_user.chatroom.nil?
        render :nothing => true
      else
        render :partial => "messages", :object => @current_chatroom
      end
    end
  end
  
end
